# models.py

from typing import Optional


class Game:
    """
    表示一个Steam游戏的数据模型。
    """
    def __init__(self, app_id: int, name: str, price: float = None, initial_price: float = None,
                 discount_percent: int = None, recommendation_percent: float = None,
                 recommendation_total: int = None, release_date: str = None,
                 is_free: bool = False, header_image_url: str = None,
                 short_description: str = None, genres: list = None):
        self.app_id = app_id
        self.name = name
        self.price = price  # 最终价格
        self.initial_price = initial_price  # 初始价格 (如果有折扣)
        self.discount_percent = discount_percent  # 折扣百分比
        self.is_free = is_free  # 是否免费
        self.recommendation_percent = recommendation_percent  # 好评率
        self.recommendation_total = recommendation_total  # 好评总数
        self.release_date = release_date  # 发布日期
        self.header_image_url = header_image_url  # 游戏头图URL
        self.short_description = short_description  # 简短描述
        self.genres = genres  # 游戏类型 (列表)

    def __repr__(self):
        """用于对象的字符串表示，便于调试"""
        return (f"Game(AppID={self.app_id}, Name='{self.name}', Price={self.price},"
                f" Rating={self.recommendation_percent}%)")

    def to_dict(self):
        """将Game对象转换为字典，便于数据存储"""
        return {
            "app_id": self.app_id,
            "name": self.name,
            "price": self.price,
            "initial_price": self.initial_price,
            "discount_percent": self.discount_percent,
            "is_free": self.is_free,
            "recommendation_percent": self.recommendation_percent,
            "recommendation_total": self.recommendation_total,
            "release_date": self.release_date,
            "header_image_url": self.header_image_url,
            "short_description": self.short_description,
            "genres": self.genres
        }

    @classmethod
    def from_dict(cls, data: dict):
        """从字典创建Game对象"""
        return cls(
            app_id=data.get("app_id"),
            name=data.get("name"),
            price=data.get("price"),
            initial_price=data.get("initial_price"),
            discount_percent=data.get("discount_percent"),
            is_free=data.get("is_free"),
            recommendation_percent=data.get("recommendation_percent"),
            recommendation_total=data.get("recommendation_total"),
            release_date=data.get("release_date"),
            header_image_url=data.get("header_image_url"),
            short_description=data.get("short_description"),
            genres=data.get("genres")
        )


class TopSellingGame:
    """
    表示Steam热销榜单中的一个游戏条目。
    """
    def __init__(self,
                 rank: int,
                 appid: Optional[int],
                 name: str,
                 price: Optional[float],
                 discount_percent: Optional[int],
                 concurrent_players: Optional[int],
                 review_percent: Optional[int] = None,   # 好评率（百分比整数）
                 review_total: Optional[int] = None      # 好评总数（整数）
                 ):
        self.rank = rank
        self.appid = appid
        self.name = name
        self.price = price
        self.discount_percent = discount_percent
        self.concurrent_players = concurrent_players
        self.review_percent = review_percent  # 好评率
        self.review_total = review_total      # 好评总数

    def __repr__(self):
        price_str = f"${self.price:.2f}" if self.price is not None else "N/A"
        discount_str = f"-{self.discount_percent}%" if self.discount_percent is not None else ""
        review_str = ""
        if self.review_percent is not None or self.review_total is not None:
            rp = f"{self.review_percent}%" if self.review_percent is not None else "N/A"
            rt = f"{self.review_total}" if self.review_total is not None else "N/A"
            review_str = f", 好评率:{rp}, 好评数:{rt}"
        concurrent_str = f"在线:{self.concurrent_players:,}" if self.concurrent_players is not None else "在线:N/A"
        return (
            f"TopSellingGame(Rank={self.rank}, AppID={self.appid}, "
            f"Name='{self.name}', Price={price_str}{discount_str}{review_str}, {concurrent_str})"
        )

    def to_dict(self):
        """
        将 TopSellingGame 对象转换为字典，便于 JSON 导出。
        """
        d = {
            "rank": self.rank,
            "appid": self.appid,
            "name": self.name,
            "price": self.price,
            "discount_percent": self.discount_percent,
            "concurrent_players": self.concurrent_players,
        }
        if self.review_percent is not None:
            d["review_percent"] = self.review_percent
        if self.review_total is not None:
            d["review_total"] = self.review_total
        return d

    @classmethod
    def from_dict(cls, data: dict):
        return cls(
            rank=data.get("rank"),
            appid=data.get("appid"),
            name=data.get("name"),
            price=data.get("price"),
            discount_percent=data.get("discount_percent"),
            concurrent_players=data.get("concurrent_players"),
            review_percent=data.get("review_percent"),
            review_total=data.get("review_total")
        )
